package com.mx.tool.form.window.qr;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.mx.tool.util.NotifyUtil;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

/**
 * @Author: 徐建鹏.
 * @create: 2021-11-10 19:14
 * @Description:
 */
public class QrJxWindow {

    private JPanel jPanel;
    private JTextArea textArea;
    private JButton jxButton;
    private JTextField textField;
    private JButton uploadButton;

    public JPanel getContent() {
        return jPanel;
    }

    public QrJxWindow() {
        jxButton.addActionListener(e -> {
            String qrUrl = textField.getText();
            if (StringUtils.isBlank(qrUrl)) {
                NotifyUtil.error("请输入二维码地址或上传二维码图片");
                return;
            }
            if(qrUrl.startsWith("http")){
                try {
                    BufferedImage bufferedImage = ImgUtil.read(new URI(qrUrl).toURL());
                    textArea.setText(QrCodeUtil.decode(bufferedImage));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    NotifyUtil.error("图片读取错误");
                }
            }else{
                File file = new File(qrUrl);
                if(file.exists() && file.isFile()){
                    textArea.setText(QrCodeUtil.decode(file));
                }else{
                    NotifyUtil.error("文件不存在或者文件类型错误");
                }
            }

        });

        //选择文件
        uploadButton.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("图片文件","jpg","jpeg","png");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(jPanel);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                //得到选择的文件
                File file = chooser.getSelectedFile();
                if (file == null || !file.exists()) {
                    NotifyUtil.error("文件选择错误");
                    return;
                }
                textField.setText(file.getAbsolutePath());
            }
        });
    }
}
